package com.it.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.it.bean.User;
import com.it.dao.UserDao;

/**
 * Servlet implementation class loginServlet
 */
@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public loginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String userName = request.getParameter("userName");
		String passWord = request.getParameter("passWord");
		if (userName == "" || userName.length() == 0) {
			request.setAttribute("userName", "用户名为空!");
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
		if (passWord == "" || passWord.length() == 0) {
			request.setAttribute("passWord", "密码为空!");
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
		UserDao userDao = new UserDao();
		User user = userDao.login(userName, passWord);
		HttpSession session = request.getSession();
		if (user != null) {
			session.setAttribute("user", user); // 存储在Session中
			request.getRequestDispatcher("admin.jsp").forward(request, response);
		} else {
			request.setAttribute("Error", "用户名或者密码错误!");
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
	}

}
